// 协议头
const head = "5AA5";
const deviceStatusOp = "6300";

/** 转16进制 */
export function toHex(value, length) {
    if(isNaN(value)){
        throw new Error(value + " is not a num");
    }
    let hex = "";
    let intValue = parseInt(value);
    if(intValue < 0) {
        let maxValue = maxValueBySize(length);
        hex = (maxValue+intValue).toString(16).toUpperCase();
    } else {
        hex = intValue.toString(16).toUpperCase();
    }
    if(hex.length > length) {
        throw new Error(value + " to hex " + hex + " length is over " + length);
    }
    let hexSize = hex.length;
    for (let i = hexSize; i < length; i++){
        hex = "0" + hex;
    }
    return hex;
}

/** 转为发送数据 valueArray=》 [ {value:11, length: length}]*/
export function toSendValue(op, registerAddress, valueArray) {
    let sendValue = op + registerAddress + toHex(valueArray.length, 2); // 最大到127 注意
    valueArray.forEach(
        function (value) {
            sendValue = sendValue + toHex(value["value"], value["length"]);
        }
    );

    let bytesLength = sendValue.length/2;
    let bytesHex = toHex(bytesLength, 2); // 最大值127 注意

    let sendStringValue =  (head + bytesHex + sendValue).toUpperCase();
    console.info(sendStringValue);
    return str2Bytes(sendStringValue)
}

function str2Bytes(str) {

    let pos = 0;
    let len = str.length;
    if(len % 2 !== 0) {
        return null;
    }

    len /= 2;
    let hexA = [];

    for (let i = 0; i < len; i++) {
        let s = str.substr(pos, 2);
        let v = parseInt(s, 16);
        hexA.push(v);
        pos += 2;
    }
    return hexA;

}


/** 抽取返回数据 5A A5 05 82 19 89 22 07*/
export function extractData(byteArray, receiveRegisterSizeJSON) {
    // 分片数据的处理
    let valueStr = bytes2HexString(byteArray).toUpperCase();
    let sendHead = valueStr.substr(0, 4);
    if(sendHead !== head){
        return [];
    }

    // 所有数据的接受
    let length = parseInt(valueStr.substr(4,2), 16);
    let op = valueStr.substr(8, 4);
    let totalValueLength = length * 2 - 6;
    if(op === deviceStatusOp) { //仪器状态接受数据处理
        return [{
            "op" : op,
            "valueLength" : totalValueLength,
            "value" : valueStr.substr(12)
        }];
    } else {
        let firstLength = receiveRegisterSizeJSON[op];
        if(isEmptyObject(firstLength)){
            // dwmAlert("该寄存器不支持 " + op);
            return;
        } else {
            // 多数据的支持
            if (firstLength >= totalValueLength){  //单个数据的返货和接口
                return [{
                    "op" : op,
                    "valueLength" : firstLength,
                    "value" : valueStr.substr(12)
                }];
            } else {  // 批量数据的发送和接口， 没有多余的数据
                let result = [];
                let start = 0;
                let opInt = parseInt(op, 16);
                let index = 0;
                let curValueLength = valueStr.length - 12;
                while (start < curValueLength) {
                    let size = receiveRegisterSizeJSON[(opInt + index).toString(16)];
                    if(isEmptyObject(size)){
                        size = 4;
                    }
                    if(start + size <= curValueLength){
                        result.push(
                            {
                                "op" :(opInt + index).toString(16),
                                "valueLength" : size,
                                "value" : valueStr.substr(12+start, size)
                            }
                        )
                    } else {
                        result.push(
                            {
                                "op" : (opInt + index).toString(16),
                                "valueLength" : size,
                                "value" : valueStr.substr(12+start)
                            }
                        )
                    }
                    index++;
                    start = start + size;
                }
                return result;
            }
        }
    }
}

function bytes2HexString (arrBytes) {
    let str = "";
    for (let i = 0; i < arrBytes.length; i++) {
        let tmp;
        let num = arrBytes[i];
        if (num < 0) {
            tmp = (255+num+1).toString(16);
        } else {
            tmp = num.toString(16);
        }
        if (tmp.length === 1) {
            tmp = "0" + tmp;
        }
        str += tmp;
    }
    return str;
}


export function maxValueBySize(size) {
    let base = 1;
    for(let i = 0; i < size; i++){
        base = base * 16;
    }
    return base;
}


export function isEmptyObject(value) {
    return value === undefined || value === null;
}

export function isEmptyString(value) {
    return value === undefined || value === null || value === "";
}

